package com.xrh.core.bean;

import java.util.List;

import com.xrh.core.interfaces.ParseQueryerInf;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;

/**
 * @function sql语句查询器
 * @author 肖荣辉
 * @date 2022年12月12日
 */
public class SQLQueryerParser implements ParseQueryerInf{
	
	public static void main(String[] args) {
		
		  //SELECT * FROM SY_GCP_PATIENT_VIEW WHERE PATIENT_NO = '1000000000' AND ROWNUM = 1 ORDER BY CREATE_DATE DESC
				  
		Queryer queryer = new Queryer();
		
		queryer.eq("PATIENT_NO", "1000000000");
		queryer.eq("ROWNUM", "1");
		
		queryer.orderByDesc("CREATE_DATE");
		
		System.out.println(new SQLQueryerParser().parseQueryer(queryer));
		
	}
	
	/**
	 * @function  解析Queryer
	 * @param queryer
	 * @author 肖荣辉
	 * @date 2022年12月12日
	 */
	public String parseQueryer(Queryer queryer) {
		
		if(queryer == null || queryer.isEmpty())
			return "";
		
		String temp = queryer.getColName() ;
		
		/**
		 * @link CompareType
		 */
		switch(queryer.getCompareType()) {
		
			//等值查询
			case EQ : 
				temp += " ='" + queryer.getCompareValue() + "'";
				break;
			
			//in查询
			case IN : 
				temp += " in('"+StrUtil.join("','", Convert.toList(String.class , queryer.getCompareValue().split(",")))+"')";
				break;
			
			//不在in里面
			case NOT_IN : 
				temp += " not in('"+StrUtil.join("','", Convert.toList(String.class , queryer.getCompareValue().split(",")))+"')";
				break;
				
			//大于	
			case GT : 
				temp += " >'" + queryer.getCompareValue() + "'";
				break;
				
			//小于	
			case LT : 
				temp += " <'" + queryer.getCompareValue() + "'";
				break;
				
			//大于等于	
			case GE : 
				temp += " >='" + queryer.getCompareValue() + "'";
				break;
			
			//小于等于	
			case LE : 
				temp += " <='" + queryer.getCompareValue() + "'";
				break;
				
			//不等于	
			case NE : 
				temp += " !='" + queryer.getCompareValue() + "'";
				break;
				
			//模糊查询	
			case LIKE : 
				temp += " like '" + queryer.getCompareValue() + "'";
				break;	
				
			//is not	
			case IS_NULL:
				temp += " is null ";
				break;
			
			//is not null
			case IS_NOT_NULL:
				temp += " is not null ";
				break;
		}
		
		List<Queryer> complexQueryerList = queryer.getComplexQueryerList();
		
		//复合条件总是and
		for(int i = 0 ; complexQueryerList != null && i < complexQueryerList.size() ; i ++) {
			
			Queryer item  = complexQueryerList.get(i);
			
			temp += " and (" + parseQueryer(item) + ")";
			
		}
		
		if(queryer.getNextQueryer() != null) {
			String andOrTxt = queryer.isAndNextQueryer() ? " and " : " or " ;
			temp += andOrTxt + parseQueryer(queryer.getNextQueryer());
		}
	
		temp = temp.trim();
		
		temp = temp.startsWith("and") ? temp.replace("and", "") : temp;
		
		temp = temp.startsWith("or") ? temp.replace("or", "") : temp;
			
		return temp;
	}
	
}
